<template>
  <div>
    <el-dialog
      top="3%"
      :visible.sync="visible"
      :title="gridFormType"
      :before-close="modalClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="70%"
      size="small"
    >
      <el-card class="box-card" style="margin-top: -30px; background: #fafafa;">
        <el-divider style="padding: 0px; margin: 0px;" />
        <el-row :gutter="10">
          <el-col :xs="24" :sm="14">
            <el-form ref="form" :model="form" :rules="rules" label-position="right" label-width="100px">
              <el-form-item label="上级网格" prop="parentGuid">
                <treeselect
                  v-model="form.parentGuid"
                  :multiple="false"
                  :options="gridTree"
                  clear-value-text="删除"
                  placeholder="请选择上级网格"
                  style="width:100%"
                  @select="parentGuidSelectChange"
                />
              </el-form-item>
              <el-form-item label="网格名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入网格名称" />
              </el-form-item>
              <el-form-item label="所属部门" prop="deptGuid">
                <treeselect
                  v-model="form.deptGuid"
                  :multiple="false"
                  :options="deptGuidTree"
                  clear-value-text="删除"
                  placeholder="请选择所属部门"
                  style="width:100%"
                  @select="deptGuidSelectChange"
                />
              </el-form-item>
              <el-form-item label="所属省" prop="province">
                <el-select v-model="form.province" placeholder="请选择所属省" filterable clearable style="width: 100%;" @change="getCitymodelChange(form.province, true)">
                  <el-option v-for="item of provinceList" :key="item.label" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="所属地市" prop="city">
                <el-select v-model="form.city" placeholder="请选择所属地市" filterable clearable style="width: 100%;" @change="getCountyModelChange(form.city, true)">
                  <el-option v-for="item of cityList" :key="item.label" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="所属区县" prop="county">
                <el-select v-model="form.county" placeholder="所属区县" filterable clearable style="width: 100%;">
                  <el-option v-for="item of countyList" :key="item.label" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="经度" prop="longitude">
                <el-input v-model="form.longitude" />
              </el-form-item>
              <el-form-item label="纬度" prop="latitude">
                <el-input v-model="form.latitude" />
              </el-form-item>
              <el-form-item label="序号" prop="orderNum">
                <el-input-number v-model="form.orderNum" @change="handleOrderNumChange" />
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :xs="24" :sm="10">
            <baidu-map
              class="bm-view"
              :center="center"
              :zoom="zoom"
              :scroll-wheel-zoom="true"
              @click="getClickInfo"
              @moving="syncCenterAndZoom"
              @moveend="syncCenterAndZoom"
              @zoomend="syncCenterAndZoom"
            >
              <bm-view style="width: 100%; height:500px;" />
              <bm-marker :position="{lng: center.lng, lat: center.lat}" :dragging="true" animation="BMAP_ANIMATION_BOUNCE" @click="lookDetail(center)">
                <bm-info-window :title="infoWindow.info.title" :position="{lng: infoWindow.info.lng, lat: infoWindow.info.lat}" :show="center.showFlag" @close="infoWindowClose(center)" @open="infoWindowOpen(center)">
                  上级网格：{{ parentName }}<br>
                  网格名称：{{ form.name }}<br>
                  所属部门：{{ deptName }}<br>
                  经度：{{ infoWindow.info.lng }}<br>
                  纬度：{{ infoWindow.info.lat }}
                </bm-info-window>
              </bm-marker>
              <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :show-address-bar="true" :auto-location="true" />
              <bm-control>
                <bm-auto-complete v-model="keyword" :sug-style="{zIndex: 999999}">
                  <el-input v-model="keyword" type="text" suffix-icon="el-icon-search" placeholder="请输入搜索关键字" class="serachinput" />
                </bm-auto-complete>
              </bm-control>
              <bm-local-search :keyword="keyword" :auto-viewport="true" style="width:0px;height:0px;overflow: hidden;" />
            </baidu-map>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="8" :offset="10">
            <el-button icon="el-icon-close" style="margin-right: 5%;" @click="modalClose">取消</el-button>
            <el-button type="primary" :v-loading="submitLoading" :icon="elIconType" @click="submit">{{ gridFormType=== '新增' ? this.$t('common.add') : this.$t('common.edit') }}</el-button>
          </el-col>
        </el-row>
      </el-card>
    </el-dialog>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import { BaiduMap, BmControl, BmView, BmGeolocation, BmAutoComplete, BmLocalSearch, BmMarker } from 'vue-baidu-map'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import dataFormMixins from '@/mixins/data-form-mixins'
import gridManageApi from '@/api/grid-manage'
export default {
  name: 'GridForm',
  components: {
    Treeselect,
    BaiduMap,
    BmView,
    BmControl,
    BmGeolocation,
    BmMarker,
    BmLocalSearch,
    BmAutoComplete
  },
  mixins: [dataFormMixins],
  props: {
    visible: {
      type: Boolean,
      default() {
        return false
      }
    },
    gridFormType: {
      type: String,
      default() {
        return '新增'
      }
    },
    elIconType: {
      type: String,
      default: 'el-icon-document-add'
    },
    formData: {
      type: Object,
      default() {
        return {}
      }
    },
    // 初始化地图中心点
    center: {
      type: Object,
      default() {
        return {
          lng: {
            type: Number,
            default() {
              return 108.30
            }
          },
          lat: {
            type: Number,
            default() {
              return 22.83
            }
          },
          showFlag: {
            type: Boolean,
            default() {
              return false
            }
          }
        }
      }
    },
    // 搜索关键字
    recKeyword: {
      type: String,
      default() {
        return ''
      }
    }
  },
  data: () => {
    return {
      keyword: '',
      parentName: '',
      deptName: '',
      gridTree: [],
      deptGuidTree: [],
      cityList: [],
      countyList: [],
      provinceList: [],
      rules: {
        // parentGuid: [
        //   { required: true, message: '必填项不能为空', trigger: 'blur' }
        // ],
        name: [
          { required: true, message: '必填项不能为空', trigger: 'blur' }
        ],
        deptGuid: [
          { required: true, message: '必填项不能为空', trigger: 'blur' }
        ],
        longitude: [
          { required: true, message: '必填项不能为空', trigger: 'blur' }
        ],
        latitude: [
          { required: true, message: '必填项不能为空', trigger: 'blur' }
        ]
      },
      submitLoading: false,
      // 地图部分
      zoom: 15,
      // 地图你解析方法实例
      infoWindow: {
        info: {
          title: '当前位置信息：',
          lng: 0,
          lat: 0
        }
      }
    }
  },
  mounted() {
    this.form = this.initGrid()
    this.rules = this.initGridRules()
    this.keyword = this.recKeyword
    if (this.gridFormType === '修改') {
      this.getDetail()
    } else if (this.gridFormType === '新增') {
      this.parentName = this.form.parentGuid
      this.deptName = this.form.deptGuid
      console.log('form:', this.form)
    }
  },
  created() {
    this.initGridTree()
    this.initDeptGuidTree()
    this.getPorvinceModelChange()
  },
  methods: {
    initGridRules() {
      return {
        // parentGuid: this.getValidatorForm(),
        name: this.getValidatorForm(),
        deptGuid: this.getValidatorForm(),
        longitude: this.getValidatorForm(),
        latitude: this.getValidatorForm()
      }
    },
    initGrid() {
      return {
        id: '',
        guid: '',
        guids: '',
        parentGuid: null, // 上级网格
        name: '', // 网格名称
        deptGuid: null, // 所属部门
        level: 0, // 网格层级
        longitude: 0, // 经度
        latitude: 0, // 纬度
        province: '', // 所属省
        city: '', // 所属市
        county: '', // 所属区县
        orderNum: 0, // 排序
        zoonId: '', // 区域编码
        createTimeFrom: '',
        createTimeTo: '',
        fullPath: '', // 网格路径
        fullPathText: '', // 网格路径文本
        isDel: 0 // 是否删除
      }
    },
    getDetail() {
      this.detailObj = { ...this.formData }
      console.log('detailObj:', this.formData)
      this.detailObj.deptGuid = this.detailObj.deptId
      this.parentName = this.detailObj.parentName
      this.deptName = this.detailObj.deptName
      this.form.id = this.detailObj.id
      this.form.parentGuid = this.detailObj.parentGuid
      this.form.deptGuid = this.detailObj.deptGuid
      this.form.name = this.detailObj.name
      this.form.longitude = this.detailObj.longitude
      this.form.latitude = this.detailObj.latitude
      this.form.province = this.detailObj.province
      this.form.city = this.detailObj.city
      this.form.county = this.detailObj.county
      this.form.zoonId = this.detailObj.zoonId
      this.form.fullPath = this.detailObj.fullPath
      this.form.fullPathText = this.detailObj.fullPathText
      this.form.createTimeFrom = this.detailObj.createTimeFrom
      this.form.createTimeTo = this.detailObj.createTimeTo
      this.form.isDel = this.detailObj.isDel
      this.form.level = this.detailObj.level
      this.form.guid = this.detailObj.guid
      this.form.zoonId = this.detailObj.zoonId
      this.form.orderNum = this.detailObj.orderNum
    },
    initGridTree() {
      this.$get('main/grid/tree').then(res => {
        if (res.status === 200) {
          const resJson = res.data
          this.gridTree = resJson.data.rows
          this.gridTree.forEach((ele, idx, arr) => {
            arr[idx].checked = false
          })
          // console.log('gridTree:', this.gridTree)
        } else {
          this.$message({
            showClose: true,
            message: res.statusText,
            type: 'error',
            duration: 4000
          })
        }
      })
    },
    initDeptGuidTree() {
      this.$get('system/dept').then((r) => {
        this.deptGuidTree = r.data.data.rows
      })
    },
    getPorvinceModelChange() {
      gridManageApi.getPositionList({ level: 1 }).then(res => {
        if (res.status === 200) {
          const resJson = res.data
          const list = resJson.data
          this.provinceList = []
          this.cityList = []
          this.countyList = []
          list.forEach(ele => {
            this.provinceList.push({
              label: ele.positionName,
              value: ele.codeId
            })
          })
          if (this.form.id !== '' && this.form.id !== null && this.form.id !== undefined) {
            this.provinceList.forEach(ele => {
              if (this.form.province === ele.label) {
                const codeId = ele.value
                this.getCitymodelChange(codeId, false)
              }
            })
          }
        } else {
          this.$message({
            showClose: true,
            message: res.statusText,
            type: 'error',
            duration: 4000
          })
        }
      })
    },
    getCitymodelChange(codeId, boolean) {
      if (boolean) {
        this.form.city = ''
        this.form.county = ''
      }
      gridManageApi.getPositionList({ parentCodeId: codeId }).then(res => {
        if (res.status === 200) {
          const resJson = res.data
          const list = resJson.data
          this.cityList = []
          this.countyList = []
          list.forEach(ele => {
            this.cityList.push({
              label: ele.positionName,
              value: ele.codeId
            })
          })
          if (this.form.id !== '' && this.form.id !== null && this.form.id !== undefined) {
            this.cityList.forEach(ele => {
              if (this.form.city === ele.label) {
                const codeId = ele.value
                if (boolean === false) {
                  this.form.city = codeId
                }
                this.getCountyModelChange(codeId, false)
              }
            })
          }
        } else {
          this.$message({
            showClose: true,
            message: res.statusText,
            type: 'error',
            duration: 4000
          })
        }
      })
    },
    getCountyModelChange(codeId, boolean) {
      if (boolean) {
        this.form.county = ''
      }
      gridManageApi.getPositionList({ parentCodeId: codeId }).then(res => {
        if (res.status === 200) {
          const resJson = res.data
          const list = resJson.data
          this.countyList = []
          list.forEach(ele => {
            this.countyList.push({
              label: ele.positionName,
              value: ele.codeId
            })
          })
          if (this.form.id !== '' && this.form.id !== null && this.form.id !== undefined) {
            this.countyList.forEach(ele => {
              if (boolean === false) {
                if (this.form.county === ele.label) {
                  this.form.county = ele.value
                }
              }
            })
          }
        } else {
          this.$message({
            showClose: true,
            message: res.statusText,
            type: 'error',
            duration: 4000
          })
        }
      })
    },
    modalClose() {
      this.$emit('update:visible', false) // 直接修改父组件的属性
    },
    handleOrderNumChange(val) {
      this.form.orderNum = val
    },
    parentGuidSelectChange(val) {
      this.parentName = val
    },
    deptGuidSelectChange(val) {
      console.log(12312)
      this.deptName = val
    },
    getClickInfo(e) {
      this.center.lng = e.point.lng
      this.center.lat = e.point.lat
      this.form.longitude = e.point.lng
      this.form.latitude = e.point.lat
      console.log('event:', e)
      this.infoWindowOpen(this.center)
    },
    syncCenterAndZoom(e) {
      const { lng, lat } = e.target.getCenter()
      this.center.lng = lng
      this.center.lat = lat
      this.zoom = e.target.getZoom()
    },
    lookDetail(center) {
      center.showFlag = true
    },
    // 关闭弹窗
    infoWindowClose(center) {
      center.showFlag = false
    },
    // 打开弹窗
    infoWindowOpen(center) {
      console.log('form:', this.form)
      if (this.gridFormType === '新增') {
        this.gridTree.forEach(ele => {
          if (ele.guid === this.form.parentGuid) {
            this.parentName = ele.label
          }
        })
        this.deptGuidTree.forEach(ele => {
          if (ele.id === this.form.deptGuid) {
            this.deptName = ele.label
          }
        })
      }
      center.showFlag = true
      this.infoWindow.info.lng = center.lng
      this.infoWindow.info.lat = center.lat
    },
    submit() {
      this.submitLoading = true
      this.deptGuidTree.forEach(ele => {
        if (this.form.deptGuid === ele.id) {
          this.form.deptGuid = ele.guid
        }
      })
      if (this.form.province !== '') {
        if (this.form.city !== '') {
          if (this.form.county !== '') {
            this.form.zoonId = this.form.county
          } else {
            this.form.county = ''
            this.form.zoonId = this.form.city
          }
        } else {
          this.form.county = ''
          this.form.zoonId = this.form.province
        }
      }
      console.log('form:', this.form)
      if (this.checkEmpty(this.form)) {
        let tipText = ''
        // if (this.form.parentGuid === '' || this.form.parentGuid === null) {
        //   tipText = '*上级网格为必选项'
        // } else
        if (this.form.name === '') {
          tipText = '*网格名称为必填项'
        } else if (this.form.deptGuid === '' || this.form.deptGuid === null) {
          tipText = '*所属部门为必选项'
        } else if (this.form.longitude === 0) {
          tipText = '*经度为必填项'
        } else if (this.form.longitude === 0) {
          tipText = '*纬度为必填项'
        }
        this.$message({
          showClose: true,
          message: tipText + '不能为空',
          type: 'error',
          duration: 4000
        })
        return
      }
      if (this.gridFormType === '新增') {
        this.submitCreateForm()
      } else if (this.gridFormType === '修改') {
        this.submitEditForm()
      }
    },
    submitCreateForm() {
      const model = this.formatFormData(this.form)
      gridManageApi.addGrid(model).then(res => {
        if (res.status === 200) {
          this.$message({
            showClose: true,
            message: '提交成功！',
            type: 'success',
            duration: 4000
          })
          this.form = this.initGrid()
          this.loading = false
          this.$emit('submit', 'add')
          this.$emit('update:visible', false)
        } else {
          this.$message({
            showClose: true,
            message: res.statusText,
            type: 'error',
            duration: 4000
          })
          this.loading = false
        }
      }).catch(() => {
        this.submitLoading = false
      })
    },
    submitEditForm(api) {
      const model = this.formatFormData(this.form)
      gridManageApi.updateGird(model).then(res => {
        if (res.status === 200) {
          this.$message({
            showClose: true,
            message: '修改成功！',
            type: 'success',
            duration: 4000
          })
          this.form = this.initGrid()
          this.$emit('submit', 'edit')
          this.$emit('update:visible', false)
        } else {
          this.$message({
            showClose: true,
            message: res.statusText,
            type: 'error',
            duration: 4000
          })
        }
      }).catch(() => {
        this.submitLoading = false
      })
    },
    checkEmpty(obj) {
      let empty = false
      for (const key in obj) {
        if (key === 'name' || key === 'deptGuid' || key === 'longitude' || key === 'latitude') {
          if (obj[key] === '' || obj[key] === null || obj[key] === 'null' || obj[key] === 0) {
            empty = true
          }
        }
      }
      return empty
    }
  }
}
</script>

<style>

</style>
